package com.yonyou.pmclouds.businessobject.util;

import com.yonyou.pmclouds.basecom.exception.BusinessException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 将图片的url生成对应的打印预览所要求的html
 *
 * @author yzx
 * @Date: 2018/5/30 19:14
 */
public class PrintPreviewObj2Html {
    // 暴露使用
    public static final String BASE_PREFIX = "$PRINTASHTMLGC$<br/>";
    public static final String IMG = "img";
    // 开始标签、结束标签
    private static final String START_LABLE = "<";
    private static final String SUFFIX_LABLE = ">";
    private static final String END_LABLE = "/>";
    private static final String BR = "<br/>";
    private static final String QUOTATION_MARK = "'";
    private static final String SRC = " src=";
    // 样式
    private static final String STYLE = " style=";
    private static final String WIDTH = "width:";
    private static final String HEIGHT = "height:";
    private static final String PX = "px";
    // 相片间距
    private static final String MARGIN_LEFT = "margin-left: 2px;";
    // div开始标签
    private static final String DIV = "div";
    private static final String DIV_END = "</div>";
    private static final int A4_WIDTH = 666;
    // 前缀
    private String prefix;
    // 标签
    private String label;
    // 每行显示个数
    private int perLineNum;

    private int divHeight = 0;

    public PrintPreviewObj2Html(String prefix, String label, int perLineNum) {
        this.prefix = prefix;
        this.label = label;
        this.perLineNum = perLineNum;
    }

    public String urls2Html(String[] urls) throws BusinessException{
        if (ArrayUtils.isEmpty(urls) || urls.length == 0) {
            return "";
        }

        // 过滤mp4文件
        List<String> imageList = new ArrayList<>();
        for(String url : urls){
            if(!url.contains("mp4")){
                imageList.add(url);
            }
        }

        // 减1是因为图片之间有添加缝隙，如果图片个数为偶数时为了保证图片不折叠故减小图片宽度占比
        int width;
        if(perLineNum % 2 == 0) {
            width = 100 / perLineNum -1;
        }else {
            width = 100 / perLineNum;
        }
        StringBuilder result = new StringBuilder();
        String imageLabels = getImageLabels(imageList.toArray(new String[]{}), width);
        result.append(prefix).append(START_LABLE).append(DIV).append(STYLE).append(QUOTATION_MARK);
        result.append(HEIGHT).append(divHeight).append(PX).append(QUOTATION_MARK).append(SUFFIX_LABLE);
        result.append(imageLabels);
        result.append(DIV_END);
        return result.toString();
    }

    private int getHeight(String url,int width) throws BusinessException{
        try {
            URL netUrl = new URL(url);
            BufferedImage image = ImageIO.read(netUrl);
            int imageHeight = image.getHeight();
            int imageWidth = image.getWidth();
//            int newImageWidth = (int) Math.ceil(imageWidth * width * 0.01);
            int newImageWidth = (int) Math.ceil(A4_WIDTH * width * 0.01);
            return newImageWidth * imageHeight / imageWidth;
        }catch (IOException e){
            throw new BusinessException("read image to bufferedImage : " + e.getMessage());
        }
    }

    private String getImageLabels(String[] urls, int width) throws BusinessException{
        divHeight = 0;
        int urlsLength = urls.length;
        int row = urlsLength % perLineNum > 0 ? urlsLength / perLineNum + 1 : urlsLength / perLineNum;
        StringBuilder result = new StringBuilder();
        //同一高度的图片放到一起展示
        Map<String, ArrayList<String>> imageMap = new HashMap<>();
        for(String url : urls) {
            // 图片显示高度最大不能超过240px
            int newImgHeight = this.getHeight(url, width);
            newImgHeight = newImgHeight > 240 ? 240 : newImgHeight;
            String newHeight = String.valueOf(newImgHeight);
            ArrayList<String> urlList = imageMap.get(newHeight);
            if(urlList != null && urlList.size() > 0) {
                urlList.add(url);
            }else {
                urlList = new ArrayList<>();
                urlList.add(url);
                imageMap.put(newHeight, urlList);
            }
        }
        //图片数量
        int count = 0;
        //每行当中最大高度
        int rowMaxHeight = 0;
        //循环到了第几行
        int rowTemp = 1;
        boolean lastRowHeight = false;
        for(Map.Entry<String, ArrayList<String>> entry : imageMap.entrySet()) {
            int imageHeight = Integer.valueOf(entry.getKey());
            for(String urlTemp : entry.getValue()) {
                if(imageHeight > rowMaxHeight) {
                    rowMaxHeight = imageHeight;
                }
                count++;
                result.append(getImageLabel(urlTemp, width, imageHeight));
                if(count % perLineNum == 0) {
                    rowTemp++;
                    divHeight += rowMaxHeight;
                    rowMaxHeight = 0;
                    result.append(BR);
                }else if(rowTemp == row){
//                    如果是最后一行未满，则直接把最大高度加上即可
                    lastRowHeight = true;
                }
            }
        }
        if(lastRowHeight) {
            divHeight += rowMaxHeight;
        }
        return result.toString();
    }

    private String getImageLabel(String url, int width, int height) {
        StringBuilder imageLabel = new StringBuilder();
        imageLabel.append(START_LABLE).append(label).append(STYLE);
        imageLabel.append(QUOTATION_MARK).append(WIDTH).append(width).append("%;");
        imageLabel.append(HEIGHT).append(height).append(PX).append(";");
        imageLabel.append(MARGIN_LEFT).append(QUOTATION_MARK);
        imageLabel.append(SRC).append(QUOTATION_MARK).append(url).append(QUOTATION_MARK).append(END_LABLE);
        return imageLabel.toString();
    }

    /**
     * 数字体验馆特殊转换
     * @author yzx
     * @date 2018/8/6 18:21
     * @param urls
     * @return java.lang.String
     */
    public String urls2HtmlForVisitCard(String[] urls, String height){
        if(urls == null || urls.length==0){
            return "";
        }
        int width;
        if(perLineNum % 2 == 0) {
            width = 100 / perLineNum -1;
        }else {
            width = 100 / perLineNum;
        }
        StringBuilder strImgs = new StringBuilder();
        strImgs.append(BASE_PREFIX);
        for(int i=0;i<urls.length;i++){
            strImgs.append(START_LABLE).append(label).append(STYLE);
            strImgs.append(QUOTATION_MARK).append(WIDTH).append(width).append("%;");
            //高度不定死能撑乱
            strImgs.append(HEIGHT).append(height).append("px;");
            strImgs.append(MARGIN_LEFT).append(QUOTATION_MARK);
            strImgs.append(SRC).append(QUOTATION_MARK).append(urls[i]).append(QUOTATION_MARK).append(END_LABLE);
            if(i > 0 && i % perLineNum == 0){
                strImgs.append(BR);
            }
        }
        return strImgs.toString();
    }
    public static void main(String[] args) throws BusinessException{
        PrintPreviewObj2Html obj2Html = new PrintPreviewObj2Html(BASE_PREFIX, IMG, 3);
        System.out.print(obj2Html.urls2Html(new String[]{"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=60053102,2679753292&fm=27&gp=0.jpg",
                "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2869170975,549832339&fm=27&gp=0.jpg",
                "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2860859233,3135511431&fm=27&gp=0.jpg",
                "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2860859233,3135511431&fm=27&gp=0.jpg"}));
    }
}
